﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SaveTheQueen.Component
{
    public class TextSprite : Sprite
    {
        private string text;
        private string fontResource;
        private SpriteFont font;

        public TextSprite(string text, string font, int x, int y, GameObject owner, Game game)
            : base(x, y, 0, 0, owner, game)
        {
            this.text = text;
            this.fontResource = font;
        }

        public SpriteFont Font
        {
            get { return font; }
        }
        public string Text
        {
            get { return text; }
            set { text = value; CalcCenterAndCenterOffset(sourceSize()); }
        }
        protected override Vector2 sourceSize()
        {
            if (font != null)
                return font.MeasureString(text);
            else
                return Vector2.Zero;
        }

        protected override void LoadContent()
        {
            font = Game.Content.Load<SpriteFont>(fontResource);
            Vector2 size = font.MeasureString(text);
            this.Size = size;
            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            SpriteBatch sb = ((SpriteBatch)Game.Services.GetService(typeof(SpriteBatch)));

            if (Shader != null)
            {
                sb.End();
                sb.Begin(SpriteSortMode.Deferred, null, null, null, null, Shader, Core.ScaleMatrix);

                sb.DrawString(
                    font,
                    text,
                    Position + Offset + centerOffset,
                    Tint,
                    Rotation,
                    realCenter,
                    innerScale * Scale,
                    Effect,
                    Depth);

                sb.End();   // End current pass and start the defaut one again, so the following objects won't be affected.
                sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Core.ScaleMatrix);
            }
            else
            {
                sb.DrawString(
                    font,
                    text,
                    Position + Offset + centerOffset,
                    Tint,
                    Rotation,
                    realCenter,
                    innerScale * Scale,
                    Effect,
                    Depth);
            }
            base.Draw(gameTime);
        }


    }
}
